package com.pansoft.openplanet.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.efounder.utils.EasyPermissionUtils;
import com.pansoft.nfc.acs.activity.BleNfcMessageActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.BlueToothDeviceAdapter;
import com.pansoft.openplanet.bean.CreateChildWalletBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;

/**
 * 蓝牙扫描（ble）
 *
 * @author YQS
 */

public class BleBlutoothScanActivity extends TCBaseActivity implements View.OnClickListener {
    private static final String TAG = "BleNfcBlutoothScanActivity";
    public static final int REQUEST_TO_GET_PRIV_KEY_MIDDLE = 1984;
    public static final int REQUEST_TO_ADD_CARD = 1985;
    /**
     * 蓝牙设备类型，其他，nfc，手表等
     **/
    public static final int BLE_TYPE_OTHER = 0;
    public static final int BLE_TYPE_NFC = 1;
    public static final int BLE_TYPE_WATCH = 2;
    private TextView tvTitle;
    private TextView tvSave;
    private RecyclerView recyclerView;
    private BlueToothDeviceAdapter blueToothDeviceAdapter;
    private List<BleDevice> devices = new ArrayList<>();
    private SmartRefreshLayout refreshLayout;
    private String address;
    private CreateChildWalletBean childWalletBean;
    private int bleDeviceType;
    private boolean isNewCreateWallet = false;

    private int createType;
    public static final int TYPE_CREATE_COLD_WALLET = 0;
    public static final int TYPE_ADD_CARD = 1;
    public static final int TYPE_CONVERT_WALLET = 2;
    public static final int TYPE_READ_PRIV_KEY = 3;
    public static final int TYPE_DELETE_COLD_CHILD_WALLET = 4;
    public static final int TYPE_CHANGE_PIN = 6;
    public static final int TYPE_RESET_PIN = 7;
    //是否允许扫描
    private boolean enableScan;

    /**
     * @param context
     * @param address    钱包地址
     * @param createType 创建钱包类型
     */
    public static void start(Context context, String address, int createType, int bleDeviceType) {
        Intent starter = new Intent(context, BleBlutoothScanActivity.class);
        starter.putExtra("address", address);
        starter.putExtra("createType", createType);
        starter.putExtra("bleDeviceType", bleDeviceType);
        context.startActivity(starter);
    }

    public static void start(Context context, CreateChildWalletBean childWalletBean, int createType, int bleDeviceType) {
        Intent starter = new Intent(context, BleBlutoothScanActivity.class);
        starter.putExtra("childWalletBean", childWalletBean);
        starter.putExtra("createType", createType);
        starter.putExtra("bleDeviceType", bleDeviceType);
        context.startActivity(starter);
    }

    /**
     * 添加卡片，读取uid，存在卡片，更新卡片信息，不存在则添加
     * @param context
     * @param createType
     * @param bleDeviceType
     */
    public static void start(Context context, int createType, int bleDeviceType) {
        Intent starter = new Intent(context, BleBlutoothScanActivity.class);
        starter.putExtra("createType", createType);
        starter.putExtra("bleDeviceType", bleDeviceType);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_acitivty_blt_scan);
        address = getIntent().getStringExtra("address");
        createType = getIntent().getIntExtra("createType", TYPE_CREATE_COLD_WALLET);
        if (getIntent().getExtras() != null) {
            childWalletBean = (CreateChildWalletBean) getIntent().getExtras().get("childWalletBean");
            if (address == null || "".equals(address)) {
                if ((createType == TYPE_CREATE_COLD_WALLET || createType == TYPE_CONVERT_WALLET )
                        && childWalletBean == null) {
                    return;
                }
                //新建钱包
                isNewCreateWallet = true;
            }
        }
        bleDeviceType = getIntent().getIntExtra("bleDeviceType", BLE_TYPE_OTHER);
        initView();
        initAdapter();
        checkBltPermission();
    }

    @Override
    protected void onStop() {
        super.onStop();
        BleManager.getInstance().cancelScan();
        enableScan = false;
    }

    private void initView() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.bt_please_select_device);
        tvSave = (TextView) findViewById(R.id.tv_save);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //取消扫描
                BleManager.getInstance().cancelScan();
                checkBltPermission();
                refreshLayout.finishRefresh(2000);

            }
        });
    }

    private void initAdapter() {
        blueToothDeviceAdapter = new BlueToothDeviceAdapter(this, R.layout.op_item_bluetooth_device, devices);
        recyclerView.setAdapter(blueToothDeviceAdapter);
        blueToothDeviceAdapter.setOnitemClickListener(new BlueToothDeviceAdapter.ItemClickListener() {
            @Override
            public void onItemClick(BleDevice bledevice) {
                if (BLE_TYPE_NFC == bleDeviceType) {
                    //连接nfc蓝牙
                    if (createType == TYPE_CREATE_COLD_WALLET) {
                        BleNfcMessageActivity.start(BleBlutoothScanActivity.this, bledevice,
                                childWalletBean, createType);
                    } else if (createType == TYPE_READ_PRIV_KEY) {
                        //转账等读取私钥
                        //用回调
                        Intent intent = new Intent(BleBlutoothScanActivity.this, BleNfcMessageActivity.class);
                        intent.putExtra("bleDevice", bledevice);
                        intent.putExtra("address", address);
                        intent.putExtra("createType", createType);
                        startActivityForResult(intent, REQUEST_TO_GET_PRIV_KEY_MIDDLE);
                    } else if (createType == TYPE_ADD_CARD) {
                        Intent intent = new Intent(BleBlutoothScanActivity.this, BleNfcMessageActivity.class);
                        intent.putExtra("bleDevice", bledevice);
                        intent.putExtra("address", address);
                        intent.putExtra("createType", createType);
                        startActivityForResult(intent, REQUEST_TO_ADD_CARD);
                    } else if (createType == TYPE_RESET_PIN || createType == TYPE_CHANGE_PIN) {
                        Intent intent = new Intent(BleBlutoothScanActivity.this, BleNfcMessageActivity.class);
                        intent.putExtra("bleDevice", bledevice);
                        intent.putExtra("address", address);
                        intent.putExtra("createType", createType);
                        intent.putExtra("rawPass", getIntent().getStringExtra("rawPass"));
                        intent.putExtra("newPass", getIntent().getStringExtra("newPass"));
                        intent.putExtra("cardNo", getIntent().getStringExtra("cardNo"));
                        startActivityForResult(intent, REQUEST_TO_ADD_CARD);
                    } else if (createType == TYPE_DELETE_COLD_CHILD_WALLET) {
                        Intent intent = new Intent(BleBlutoothScanActivity.this, BleNfcMessageActivity.class);
                        intent.putExtra("bleDevice", bledevice);
                        intent.putExtra("address", address);
                        intent.putExtra("createType", createType);
                        intent.putExtra("cardNo", getIntent().getStringExtra("cardNo"));
                        startActivityForResult(intent, REQUEST_TO_ADD_CARD);
                    } else {
                        BleNfcMessageActivity.start(BleBlutoothScanActivity.this, bledevice,
                                address, createType);
                    }
                } else {
                    //连接其他设备
                    BleMessageActivity.start(BleBlutoothScanActivity.this, bledevice, address);
                }

            }
        });
    }


    //检查蓝牙权限
    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_LOCATION)
    private void checkBltPermission() {
        //检查是否有蓝牙
        if (!BleManager.getInstance().isSupportBle()) {

            new AlertDialog.Builder(this).setTitle(R.string.common_text_hint).setMessage(R.string.common_text_bluetooth_not_support)
                    .setCancelable(false).setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).show();
            return;
        }


        if (!EasyPermissionUtils.checkLocationPermission()) {
            EasyPermissionUtils.requestLocationPermission(this);
        } else {
            //检查蓝牙是否打开
            if (!BleManager.getInstance().isBlueEnable()) {
                new AlertDialog.Builder(this).setTitle(R.string.common_text_hint).setMessage(R.string.common_text_please_open_bluetooth)
                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(intent, 100);
                            }
                        }).show();

                //this.startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));

            } else {
                startScanDevices();
            }
        }
    }


    private void startScanDevices() {
        enableScan = true;
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                devices.clear();
                blueToothDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (!enableScan) {
                    return;
                }
                if (TextUtils.isEmpty(bleDevice.getName())) {
                    //过滤没有名字的设备
                    return;
                }
                devices.add(bleDevice);
                blueToothDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                enableScan = false;
                LogUtils.i("停止扫描蓝牙设备");
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            checkBltPermission();
        } else if (requestCode == REQUEST_TO_GET_PRIV_KEY_MIDDLE) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK, data);
                finish();
            }
        } else if (requestCode == REQUEST_TO_ADD_CARD) {
            setResult(RESULT_OK, data);
            finish();
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        }
    }


}
